package com.youzan.cloud.biz.integral.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.youzan.cloud.biz.integral.dal.dataobj.PointChange;
import com.youzan.cloud.biz.integral.dal.dataobj.UserPoint;
import com.youzan.cloud.biz.integral.dal.mapper.PointChangeMapper;
import com.youzan.cloud.biz.integral.dal.mapper.UserPointMapper;
import com.youzan.cloud.biz.integral.service.LocalPointService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author hlin
 */
@Service
public class LocalPointServiceImpl implements LocalPointService {

    private static final Logger log = LoggerFactory.getLogger(LocalPointServiceImpl.class);

    @Autowired
    private UserPointMapper userPointMapper;
    @Autowired
    private PointChangeMapper pointChangeMapper;


    @Override
    public UserPoint getUserPoint(String yzOpenId) {

        return userPointMapper.queryUserPoint(yzOpenId);
    }

    @Override
    public List<PointChange> getUserPointDetails(String yzOpenId) {
        // TODO implement this

        return Lists.newArrayList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeUserPoint(PointChange changeInfo) {

        log.info("change user point, {}", changeInfo );
        pointChangeMapper.changePoint(changeInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createPointLog(PointChange changeInfo) {
        log.info("create point record =[{}]", JSONObject.toJSONString(changeInfo));
        return pointChangeMapper.insertChangeLog(changeInfo);
    }

    @Override
    public PointChange queryByUnique(String unique,Integer pointType,String syncStatus) {
        log.info("query point record unique=[{}]",unique);
        return pointChangeMapper.queryByUnique(unique,pointType,syncStatus);
    }
    @Override
    public boolean changeLog(String status, String bizNo, Integer pointType) {
        PointChange pointChange = PointChange.builder()
                .pointType(pointType)
                .bizNo(bizNo)
                .syncStatus(status).build();
        int ef = changeLogStatus(pointChange);
        if (ef < 0) {
            log.warn("更新积分流水状态失败");
            return false;
        }
        return true;
    }
    @Override
    public int changeLogStatus(PointChange pointChange) {

        return pointChangeMapper.changeStatus(pointChange);
    }
}
